package com.cn.ycy.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.cn.ycy.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.server.ServerWebExchange;

public class RequestUtil {

	private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);


	public static PathInfo getPathInfo(ServerWebExchange exchange)  throws BusinessException {
		PathInfo pathInfo = exchange.getAttribute(WebExchangeAttributeKey.PATH_INFO);
		if (pathInfo == null) {
			pathInfo=new PathInfo();
			fillPathInfo(pathInfo,exchange);
			exchange.getAttributes().put(WebExchangeAttributeKey.PATH_INFO, pathInfo);
		}
		return pathInfo;
	}
	private static void fillPathInfo(PathInfo pathInfo, ServerWebExchange exchange){
		String requestPath = exchange.getRequest().getURI().getPath();
		try {
			String[] paths=requestPath.split("/");
			if(paths!=null&&paths.length>2){
				pathInfo.setServicePath(paths[1]);
				pathInfo.setAppUnique(paths[2]);
				pathInfo.setRealPath("/"+requestPath.substring(requestPath.indexOf(paths[3])));

				ObjectMapper jsonMapper = new ObjectMapper();
				logger.info(jsonMapper.writeValueAsString(pathInfo));
			}
		} catch (Exception e) {
			logger.error("fillPathInfo exception!", e);
		}

	}
    public static String getRequestMethod(ServerWebExchange exchange) {
        return exchange.getRequest().getMethod().name();
    }



}
